package cn.pfund.util;

import java.math.BigDecimal;

/**
 * @author zhangzhen
 *
 */
public class MathUtil {
	/**
	 * 小数位精确方式
	 */
	public enum RoundType {

		/** 四舍五入 */
		roundHalfUp("四舍五入"),

		/** 向上取整 */
		roundUp("向上取整 "),

		/** 向下取整 */
		roundDown("向下取整");
		private String key;
		private String value;
		private RoundType(String value){
			this.key = this.name();
			this.value=value;
		}
		public static RoundType fromString(String key) {
			return Enum.valueOf(RoundType.class, key);
		}
		public String getKey() {
			return this.key;
		}
		public String getValue() {
			return this.value;
		}
	}
	/**
	 * 带精度的除法运算，小数位按照四舍五入方式精确
	 * @param num 除数
	 * @param divide 被除数
	 * @param scale 保留位数
	 * @return
	 */
	public static double divide(double num,double divide, int scale) {
		return divide(num,divide,scale,RoundType.roundHalfUp);
	}
	/**
	 * 带精度的除法运算
	 * @param num 除数
	 * @param divide 被除数
	 * @param scale 保留位数
	 * @param roundType  小数位精确方式
	 * @return
	 */
	public static double divide(double num,double divide,int scale,RoundType roundType) {		
		return divide(new BigDecimal(num),new BigDecimal(divide),scale,roundType).doubleValue();
	}
	/**
	 * 带精度的除法运算，小数位按照四舍五入方式精确
	 * @param num 除数
	 * @param divide 被除数
	 * @param scale 保留位数
	 * @return
	 */
	public static BigDecimal divide(BigDecimal num,BigDecimal divide, int scale) {
		return divide(num,divide,scale,RoundType.roundHalfUp);
	}
	/**
	 * 带精度的除法运算
	 * @param num 除数
	 * @param divide 被除数
	 * @param scale 保留位数
	 * @param roundType  小数位精确方式
	 * @return
	 */
	public static BigDecimal divide(BigDecimal num,BigDecimal divide,int scale,RoundType roundType) {
		if(divide!=null&&divide.equals(new BigDecimal(0))){
			divide=new BigDecimal(1);
		}
		int roundingMode;
		if (roundType == RoundType.roundUp) {
			roundingMode = BigDecimal.ROUND_UP;
		} else if (roundType == RoundType.roundDown) {
			roundingMode = BigDecimal.ROUND_DOWN;
		} else {
			roundingMode = BigDecimal.ROUND_HALF_UP;
		}
		return num.divide(divide, scale,
				roundingMode);
	}
	public static void main(String[] args) {
		System.out.println("四舍五入：" + MathUtil.divide(90.575,0,2));//default
		System.out.println("四舍五入：" + MathUtil.divide(90.574,1,0,RoundType.roundHalfUp));
		System.out.println("向上取整：" + Integer.valueOf((int)MathUtil.divide(90.474,1,0,RoundType.roundUp)));
		System.out.println("向下取整：" + MathUtil.divide(90.579,1,0,RoundType.roundDown));
		System.out.println(MathUtil.divide(14,3,2));
	}
}
